"""

使用预先定义好的一些estimator [classifier/regresser]两类 这里以分类为例
BaselineClassifier : 统计各类别的样本 然后根据概率随机猜测 所以可以不用
LinerClassifier 
DNNClassifier
BoostTreeClassifier

"""

import pandas as pd 
import tensorflow as tf
from tensorflow import keras 
import os

# 准备数据集 
train_file = './tf_estimator/titanic/train.csv'
eval_file = './tf_estimator/titanic/eval.csv'
train_df = pd.read_csv(train_file)
eval_df = pd.read_csv(eval_file)
train_y = train_df.pop('survived')  
eval_y = eval_df.pop('survived')

def make_datasets(train_df,train_y,epochs=10,shuffle=True,batch_size=32):
      datasets = tf.data.Dataset.from_tensor_slices((dict(train_df),train_y)) 
      if shuffle:
            datasets = datasets.shuffle(10000)
      datasets = datasets.repeat(epochs).batch(batch_size)
      return datasets

train_datasets = make_datasets(train_df,train_y)
eval_datasets = make_datasets(eval_df,eval_y)


# 定义特征工程方式 
categorical_features = ['sex','n_siblings_spouses','parch','class','deck','embark_town','alone'] 
numeric_features = ['age','fare']  
feature_columns = []  

for categorical_feature in categorical_features:
      vocab = train_df[categori_feature].unique()  
      feature_columns.append(  
        tf.feature_column.categorical_column_with_vocabulary_list(categorical_feature,vocab)
      )  

for numeric_feature in numeric_features:
      feature_columns.append(
        tf.feature_column.numeric_column(numeric_feature,dtype=tf.float32)
      )  

# LinearClassifier
linear_output_file = './tf_estimator/linear_estimator'  # 定义一个存放训练结果的文件夹
if not os.path.exists(linear_output_file):
    os.mkdir(linear_output_file)

linear_estimator = tf.estimator.LinearClassifier(
    model_dir = linear_output_file,n_classes=2,feature_columns=feature_columns
    )
linear_estimator.train(input_fn=lambda  : make_datasets(train_df,train_y,epochs=10))
linear_estimator.evaluate(input_fn=lambda  : make_datasets(eval_df,eval_y,epochs=1))

# DNNClassifier
# BoostTreeClassifier
# 定义方法一致 具体参数看官方文档 如DNN要定义网络结构  hidden_units=[128,64,10] 






